<template>
    <div class="content">
        <cl-crud @load="onLoad">
            <template #slot-filter>
                <div class="filter-list">
<!--                    <div class="filter-item">-->
<!--                        <span class="filter-title">售后类型：</span>-->
<!--                        <el-select-->
<!--                                size="mini"-->
<!--                                filterable-->
<!--                                placeholder="请选择售后类型"-->
<!--                                style="width: 140px"-->
<!--                                v-model="selects.type"-->
<!--                                @change="val => refresh({ type: val, page: 1 })"-->
<!--                        >-->
<!--                            <el-option value label="全部"></el-option>-->
<!--                            <el-option :label="item.label" :value="item.value" v-for="item in postSaleType" :key="item.label"></el-option>-->
<!--                        </el-select>-->
<!--                    </div>-->
                    <div class="filter-item">
                        <span class="filter-title">售后状态：</span>
                        <el-select
                                size="mini"
                                filterable
                                placeholder="请选择售后状态"
                                style="width: 140px"
                                v-model="selects.status"
                                @change="val => refresh({ status: val, page: 1 })"
                        >
                            <el-option value label="全部"></el-option>
                            <el-option :label="item.label" :value="item.value" v-for="item in postSaleStatus" :key="item.label"></el-option>
                        </el-select>
                    </div>
                    <div class="filter-item">
                        <span class="filter-title">支付方式：</span>
                        <el-select
                                size="mini"
                                filterable
                                placeholder="请选择支付方式"
                                style="width: 140px"
                                v-model="selects.payType"
                                @change="val => refresh({ payType: val, page: 1 })"
                        >
                            <el-option value label="全部"></el-option>
                            <el-option label="支付宝" :value="1"></el-option>
                            <el-option label="微信" :value="2"></el-option>
                        </el-select>
                    </div>
                    <div class="filter-item">
                        <span class="filter-title">申请时间：</span>
                        <date-picker
                                @change="
								val => crud.refresh({ startPostsaleTime: val[0], endPostsaleTime: val[1], page: 1 })
							"
                                @refresh="crud.refresh({ startPostsaleTime: '', endPostsaleTime: '', page: 1 })"
                        ></date-picker>
                    </div>
                </div>
            </template>
            <template #slot-total>
                <div class="total-list">
                    <div class="total-item">
                        <h3>订单数量(件)</h3>
                        <p>{{ subData.orderNum }}</p>
                    </div>
                    <div class="total-item">
                        <h3>商品数量(件)</h3>
                        <p>{{ subData.goodsCount }}</p>
                    </div>
                </div>
            </template>
            <template #table-column-userInfo="{ scope }">
                <div class="user-info">
                    <p>{{ scope.row.username }}</p>
                    <p>{{ scope.row.phone }}</p>
                </div>
            </template>
            <template #table-column-goodsInfo="{ scope }">
                <div class="goods-info">
                    <img :src="scope.row.pic" />
                    <div class="goods-content">
                        <p>{{ scope.row.title }}</p>
                        <p>默认 | <span class="red">¥{{ scope.row.amount }}</span> | x{{ scope.row.count }}</p>
                    </div>
                </div>
            </template>
            <template #table-column-refund="{ scope }">
                <p class="red">¥{{ scope.row.refund }}</p>
            </template>
            <template #table-column-payment="{ scope }">
                <p class="red">¥{{ scope.row.payment }}</p>
            </template>
            <template #slot-operate="{ scope }">
                <div class="operate-list">
                    <el-button type="text" size="small" @click="orderDetail(scope.row)">订单详情</el-button>
                    <el-button type="text" size="small" @click="renewPsOrder(scope.row)" v-if="scope.row.psStatus === 0">审核订单</el-button>
                    <el-button type="text" size="small" @click="backFinish(scope.row)" v-if="scope.row.type === 2 && scope.row.status === 6">退货完成</el-button>
                    <el-button type="text" size="small" @click="confirmReceive(scope.row)" v-if="(scope.row.type === 3 || scope.row.type === 4) && scope.row.status === 6">确认收货</el-button>
                    <el-button type="text" size="small" @click="logisticsInfo(scope.row)" v-if="(scope.row.type === 3 || scope.row.type === 4) && scope.row.status === 9">填写物流</el-button>
                    <el-button type="text" size="small" @click="exchangeOrRepairFinish(scope.row)" v-if="(scope.row.type === 3 || scope.row.type === 4) && scope.row.status === 10">{{ scope.row.type === 3 ? '换货' : '返修' }}完成</el-button>
                </div>
            </template>
        </cl-crud>

        <cl-form ref="cl-form" key="after"></cl-form>
    </div>
</template>

<script>
	import postSaleStatusJs from './public/postSaleStatus.js';
	import postSaleType from './public/postSaleType.js';
	import expressType from './public/expressType.js';
	import DatePicker from '@/components/DatePicker';
	import PostSaleDetail from './components/PostSaleDetail';
	import LogisticsInfo from './components/LogisticsInfo';
	export default {
		name: 'after',
		components: {
			DatePicker,
		},
		data() {
			return {
				selects: {
					type: '',
					status: '',
					payType: '',
				},
				selectRow: [],
				subData: {
					orderNum: 0,
					goodsCount: 0
				},
				postSaleStatus: postSaleStatusJs,
				postSaleType: postSaleType,
				expressType: expressType,
			}
		},
		methods: {
			onLoad({ ctx, app }) {
				this.crud = app;
				ctx.service(this.$service.order.after)
					.set('table', {
						columns: [
							{
								type: 'index',
								label: '序号',
								align: 'center',
								width: '60px'
							},
							{
								label: '售后订单号',
								prop: 'tradeNo',
								align: 'center',
								width: 200
							},
							{
								label: '用户信息',
								prop: 'userInfo',
								align: 'center',
								width: 150
							},
							{
								label: '商品信息',
								prop: 'goodsInfo',
								align: 'left',
								width: 350
							},
							{
								label: '售后类型',
								prop: 'type',
								align: 'center',
								dict: this.postSaleType
							},
							{
								label: '审核状态',
								prop: 'status',
								align: 'center',
								dict: this.postSaleStatus
							},
							{
								label: '退款金额',
								prop: 'refund',
								align: 'center',
							},
							{
								label: '订单时间',
								prop: 'orderCreateTime',
								align: 'center',
								width: 150,
								sortable: 'custom'
							},
							{
								label: '申请时间',
								prop: 'createTime',
								width: 150,
								align: 'center',
								sortable: 'custom'
							}
						],
						props: {
							'default-sort': {
								prop: 'createTime',
								order: 'descending'
							}
						},
						op: {
							layout: ['slot-operate']
						},
						on: {
							'selection-change': selection => {
								this.selectRow = selection;
							}
						}
					})
					.set('upsert', {
						props: {
							title: '请输入回复内容',
							width: '500px',
							labelWidth: '0px'
						},
						items: [
							{
								prop: 'title',
								component: {
									name: 'el-input',
									attrs: {
										type: 'textarea',
										placeholder: '请输入回复内容',
										clearable: true
									}
								},
								rules: [
									{
										required: true,
										message: '回复内容不能为空'
									}
								]
							},
						]
					})
					.set('layout', [
						['refresh-btn', 'slot-btn', 'slot-filter', 'flex1', 'search-key'],
						['slot-total'],
						['data-table'],
						['flex1', 'pagination']
					])
					.on('refresh', async (params, { next, render }) => {
						const { list, subData } = await next(params);
						this.subData = subData;
						render(list);
					})
					.done();
				app.refresh();
			},
			refresh(params) {
				this.crud.refresh(params);
			},
            // 订单详情
			orderDetail(item) {
				let that = this;
				this.$refs['cl-form'].open({
					props: {
						title: '售后详情',
						width: '850px',
						showClose: false,
						'label-width': '0px',
						'custom-class': ''
					},
					items: [
						{
							prop: 'PostSaleDetail',
							value: item,
							component: PostSaleDetail
						},
					],
					op: {
						visible: false
					}
				})
			},
			// 审核订单
			renewPsOrder(item) {
				let that = this;
				this.$refs['cl-form'].open({
					props: {
						title: '审核订单',
						width: '500px',
						showClose: false,
						'label-width': '120px',
						'custom-class': ''
					},
					items: [
						{
							prop: 'status',
							label: '审核状态：',
                            value: 1,
							component: {
								name: 'el-select',
								attrs: {
									placeholder: '请选择审核状态',
									clearable: true
								},
								options: [
                                    {
                                    	label: '审核通过',
                                        value: 1
                                    },
									{
										label: '审核失败',
										value: 2
									}
                                ]
							},
							rules: [
								{
									required: true,
									message: '物流公司不能为空'
								}
							],
						},
						{
							prop: 'refuseReason',
							label: '失败原因：',
							component: {
								name: 'el-input',
								attrs: {
									placeholder: '请输入失败原因',
									clearable: true,
                                    type: 'textarea'
								}
							}
						},
					],
					op: {
						visible: true
					},
					on: {
						submit: ({ data, done, close }) => {
							let params = {
								postSaleId: item.id,
                            }
							if (data.status === 2) {
								if (!data.refuseReason) {
									this.$message.error('失败原因不能为空');
									done();
									return false
                                }
								params.status = data.status;
								params.refuseReason = data.refuseReason;
                            } else {
								// 根据售后类型分发状态码
                                if (item.type === 1) {
                                	// 退款
									params.status = 3;
                                } else if (item.type === 2) {
                                	// 退货
									params.status = 5;
                                } else if (item.type === 3) {
									// 换货
									params.status = 5;
								}  else if (item.type === 4) {
									// 返修
									params.status = 5;
								}
                            }
							this.$service.order.after.renewPsOrder(params).then(() => {
								that.crud.refresh();
								close();
							}).catch(err => {
								that.$message.error(err);
								done();
							});
						}
					}
				});
            },
			// 退货完成
			backFinish(item) {
				this.$confirm('订单状态修改后无法恢复，请谨慎操作！', '您确定此订单已完成退货流程？', {
					confirmButtonText: '确认完成',
					cancelButtonText: '考虑一下',
					type: 'warning'
				}).then(() => {
					this.$service.order.after.renewPsOrder({
						postSaleId: item.id,
                        status: 3 // 进入退款中流程
                    }).then(() => {
						this.crud.refresh();
					}).catch(err => {
						this.$message.error(err);
					});
				})
            },
            // 确认收货（换货&返修）
			confirmReceive(item) {
				this.$confirm('订单状态修改后无法恢复，请谨慎操作！', '您确定此订单已收到换货/返修商品？', {
					confirmButtonText: '确认完成',
					cancelButtonText: '考虑一下',
					type: 'warning'
				}).then(() => {
					this.$service.order.after.renewPsOrder({
						postSaleId: item.id,
						status: 9 // 进入待回寄流程
					}).then(() => {
						this.crud.refresh();
					}).catch(err => {
						this.$message.error(err);
					});
				})
            },
            // 填写回寄物流
			logisticsInfo(item) {
				let that = this;
				this.$refs['cl-form'].open({
					props: {
						title: '换货物流',
						width: '850px',
						showClose: false,
						'label-width': '100px',
                        'custom-class': 'logistics-info'
					},
					items: [
						{
							prop: 'logisticsInfo',
							value: item,
							component: LogisticsInfo,
						},
						{
							prop: 'expressName',
							label: '快递公司：',
                            span: 12,
							component: {
								name: 'el-select',
								attrs: {
									placeholder: '请选择快递公司',
									clearable: true
								},
								options: this.expressType
							},
							rules: [
								{
									required: true,
									message: '快递公司不能为空'
								}
							]
						},
						{
							prop: 'expressNo',
							label: '快递单号：',
							span: 12,
							component: {
								name: 'el-input',
								attrs: {
									placeholder: '请输入快递单号',
									clearable: true
								}
							},
							rules: [
								{
									required: true,
									message: '快递单号不能为空'
								}
							]
						},
					],
					op: {
						visible: true
					},
					on: {
						submit: ({ data, done, close }) => {
							let logisticsReturnMsg = {
								...item.logisticsReturnMsg
                            };
							logisticsReturnMsg.expressName = data.expressName;
							logisticsReturnMsg.expressNo = data.expressNo;

							this.$service.order.after.renewPsOrder({
								postSaleId: item.id,
								logisticsReturnMsg: JSON.stringify(logisticsReturnMsg),
                                status: 10
                            }).then(() => {
								that.crud.refresh();
								close();
							}).catch(err => {
								that.$message.error(err);
								done();
							});
						}
					}
				})
            },
			// 换货或返修完成
            exchangeOrRepairFinish(item) {
				this.$confirm('订单状态修改后无法恢复，请谨慎操作！', '您确定此订单已完成换货/返修流程？', {
					confirmButtonText: '确认完成',
					cancelButtonText: '考虑一下',
					type: 'warning'
				}).then(() => {
					this.$service.order.after.renewPsOrder({
						postSaleId: item.id,
						status: 15 // 进入已完成流程
					}).then(() => {
						this.crud.refresh();
					}).catch(err => {
						this.$message.error(err);
					});
				})
            },
		}
	};
</script>

<style lang="stylus" scoped>
    .content {
        .goods-info {
            margin-bottom: 10px;
            &:last-child {
                margin-bottom: 0;
            }
            flexBox(space-between, flex-start)
            img {
                width: 80px;
                height: 80px;
                margin-right 10px
            }
            .goods-content {
                flex: 1;
                .price {
                    span {
                        color: $main-color
                    }
                }
            }
        }
        .operate-list {
            flexBox(center, center, column);
            /deep/.el-button {
                margin-left: 0;
            }
        }
        .red {
            color: $main-color;
        }
    }
</style>